<template>
    <div class="white-box">
        <applet-tip-auth v-if="appletGrant == 0" />
        <template v-else>
            <title-more title="小程序支付设置" />
            <cell-tip show-more :datas="tipArrs" bottom="24px" />
            <el-tabs v-model="tabName" @tab-click="clickTab">
                <el-tab-pane label="小程序支付配置" name="0">
                    <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="210px">
                        <el-form-item label="商户名称" prop="sh_name" v-show="!showSecret">
                            <el-input v-model.trim="ruleForm.sh_name" clearable placeholder="请输入商户名称" />
                            <div class="input-tips">微信商户名称</div>
                        </el-form-item>
                        <el-form-item label="商户名称" v-show="showSecret">
                            <p>{{ ruleForm.sh_name }}</p>
                            <div class="input-tips">微信商户名称</div>
                        </el-form-item>

                        <el-form-item label="商户号" prop="merchant_no" v-show="!showSecret">
                            <el-input v-model.trim="ruleForm.merchant_no" clearable placeholder="请输入小程序支付商户号" />
                            <div class="input-tips">小程序支付商户号，审核通过后，在微信发送的邮件中查看或者登录商户平台查看。</div>
                        </el-form-item>
                        <el-form-item label="商户号" v-show="showSecret">
                            <p>{{ ruleForm.merchant_no }}</p>
                            <div class="input-tips">小程序支付商户号，审核通过后，在微信发送的邮件中查看或者登录商户平台查看</div>
                        </el-form-item>

                        <el-form-item label="APIv3秘钥" prop="app_secret" v-show="!showSecret">
                            <el-input v-model.trim="ruleForm.app_secret" clearable placeholder="请输入微信APIv3秘钥" />
                            <div class="input-tips">在微信商户平台证书页面</div>
                        </el-form-item>
                        <el-form-item label="APIv3秘钥" v-show="showSecret">
                            <p>{{ ruleForm.app_secret_old }}</p>
                            <div class="input-tips">在微信商户平台证书页面</div>
                        </el-form-item>

                        <el-form-item label="证书序列号" v-show="ruleForm.serial_no && showSecret">
                            <p>{{ ruleForm.serial_no }}</p>
                            <div class="input-tips">证书序列号，只有配置过才会显示</div>
                        </el-form-item>
                        <el-form-item label="证书apiclient_cert.pem" prop="two_paths" required v-show="!showSecret">
                            <el-upload
                                ref="uploadTwoRef"
                                :file-list="ruleForm.fileList_two"
                                :action="actionImgUrl()"
                                :auto-upload="false"
                                :limit="1"
                                :on-exceed="(file) => handleExceed(file, 2)"
                                :on-remove="() => handleRemove(2)"
                                :on-change="(file, fileArr) => fileChange(file, fileArr, 2)"
                            >
                                <template #trigger>
                                    <el-button type="primary">选择证书</el-button>
                                </template>
                                <el-button class="downs" type="warning" @click.stop="uploadFileTwo">上传导入</el-button>
                            </el-upload>
                            <div class="input-tips">请上传小程序证书之一<code>apiclient_cert.pem</code>，注意末尾后缀名<code>.pem</code>。</div>
                        </el-form-item>
                        <el-form-item label="证书apiclient_key.pem" prop="three_paths" required v-show="!showSecret">
                            <el-upload
                                ref="uploadThreeRef"
                                :file-list="ruleForm.fileList_three"
                                :action="actionImgUrl()"
                                :auto-upload="false"
                                :limit="1"
                                :on-exceed="(file) => handleExceed(file, 3)"
                                :on-remove="() => handleRemove(3)"
                                :on-change="(file, fileArr) => fileChange(file, fileArr, 3)"
                            >
                                <template #trigger>
                                    <el-button type="primary">选择证书</el-button>
                                </template>
                                <el-button class="downs" type="warning" @click.stop="uploadFileThree">上传导入</el-button>
                            </el-upload>
                            <div class="input-tips">请上传小程序证书之一<code>apiclient_key.pem</code>，注意末尾后缀名<code>.pem</code>。</div>
                        </el-form-item>
                        <el-form-item style="margin-top: 30px">
                            <el-button class="btn-submit" type="primary" :loading="form_loading" @click="submitForm(ruleRef)">保存</el-button>
                            <el-button class="btn-submit" type="warning" @click="resetForm(ruleRef)" v-if="showSecret">重置</el-button>
                            <el-button class="btn-submit" type="info" @click="toBackOne" v-else>不想修改？点击返回</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商家转到零钱配置" name="1">
                    <el-form ref="ruleTwoRef" :model="ruleTwoForm" :rules="ruleTwoCheck" label-width="210px">
                        <el-form-item label="商户名称" prop="sh_name" v-show="!showSecretTwo">
                            <el-input v-model.trim="ruleTwoForm.sh_name" clearable placeholder="请输入商户名称" />
                            <div class="input-tips">微信商户名称</div>
                        </el-form-item>
                        <el-form-item label="商户名称" v-show="showSecretTwo">
                            <p>{{ ruleTwoForm.sh_name }}</p>
                            <div class="input-tips">微信商户名称</div>
                        </el-form-item>

                        <el-form-item label="商户号" prop="merchant_no" v-show="!showSecretTwo">
                            <el-input v-model.trim="ruleTwoForm.merchant_no" clearable placeholder="请输入小程序支付商户号" />
                            <div class="input-tips">小程序支付商户号，审核通过后，在微信发送的邮件中查看或者登录商户平台查看。</div>
                        </el-form-item>
                        <el-form-item label="商户号" v-show="showSecretTwo">
                            <p>{{ ruleTwoForm.merchant_no }}</p>
                            <div class="input-tips">小程序支付商户号，审核通过后，在微信发送的邮件中查看或者登录商户平台查看</div>
                        </el-form-item>

                        <el-form-item label="APIv3秘钥" prop="app_secret" v-show="!showSecretTwo">
                            <el-input v-model.trim="ruleTwoForm.app_secret" clearable placeholder="请输入微信APIv3秘钥" />
                            <div class="input-tips">在微信商户平台证书页面</div>
                        </el-form-item>
                        <el-form-item label="APIv3秘钥" v-show="showSecretTwo">
                            <p>{{ ruleTwoForm.app_secret_old }}</p>
                            <div class="input-tips">在微信商户平台证书页面</div>
                        </el-form-item>

                        <el-form-item label="证书序列号" v-show="ruleTwoForm.serial_no && showSecretTwo">
                            <p>{{ ruleTwoForm.serial_no }}</p>
                            <div class="input-tips">证书序列号，只有配置过才会显示</div>
                        </el-form-item>
                        <el-form-item label="证书apiclient_cert.pem" prop="two_paths" required v-show="!showSecretTwo">
                            <el-upload
                                ref="uploadTwoRef"
                                :file-list="ruleTwoForm.fileList_two"
                                :action="actionImgUrl()"
                                :auto-upload="false"
                                :limit="1"
                                :on-exceed="(file) => handleExceed(file, 2)"
                                :on-remove="() => handleRemove(2)"
                                :on-change="(file, fileArr) => fileChange(file, fileArr, 2)"
                            >
                                <template #trigger>
                                    <el-button type="primary">选择证书</el-button>
                                </template>
                                <el-button class="downs" type="warning" @click.stop="uploadFileTwo">上传导入</el-button>
                            </el-upload>
                            <div class="input-tips">请上传小程序证书之一<code>apiclient_cert.pem</code>，注意末尾后缀名<code>.pem</code>。</div>
                        </el-form-item>
                        <el-form-item label="证书apiclient_key.pem" prop="three_paths" required v-show="!showSecretTwo">
                            <el-upload
                                ref="uploadThreeRef"
                                :file-list="ruleTwoForm.fileList_three"
                                :action="actionImgUrl()"
                                :auto-upload="false"
                                :limit="1"
                                :on-exceed="(file) => handleExceed(file, 3)"
                                :on-remove="() => handleRemove(3)"
                                :on-change="(file, fileArr) => fileChange(file, fileArr, 3)"
                            >
                                <template #trigger>
                                    <el-button type="primary">选择证书</el-button>
                                </template>
                                <el-button class="downs" type="warning" @click.stop="uploadFileThree">上传导入</el-button>
                            </el-upload>
                            <div class="input-tips">请上传小程序证书之一<code>apiclient_key.pem</code>，注意末尾后缀名<code>.pem</code>。</div>
                        </el-form-item>
                        <el-form-item style="margin-top: 30px">
                            <el-button class="btn-submit" type="primary" :loading="form_loading" @click="submitTwoForm(ruleTwoRef)">保存</el-button>
                            <el-button class="btn-submit" type="warning" @click="resetFormTwo(ruleTwoRef)" v-if="showSecretTwo">重置</el-button>
                            <el-button class="btn-submit" type="info" @click="toBackTwo" v-else>不想修改？点击返回</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </template>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, onBeforeUnmount,onActivated } from "vue"
import { useBaseStore } from "@store/base"
import { onBeforeRouteLeave } from "vue-router"
import { genFileId } from "element-plus"
import AppletTipAuth from "@components/AppletTipAuth.vue"
import CellTip from "@components/cell-tip.vue"
import TitleMore from "@components/title-more.vue"

const { proxy } = getCurrentInstance()

const storeBase = useBaseStore()
const appletGrant = 1
// const appletGrant = computed(() => {
//     return storeBase.user_auth_applet // 用户端小程序是否已经授权，0否，1是
// })

const tipArrs = [
    "请确保小程序已开通支付功能。",
    "“微信小程序平台运营规范”，微信小程序内购买商品请使用微信支付",
    "小程序安全证书请登录微信支付商户平台中进行下载证书",
    "重置：点击之后可重新配置",
]

// 离开-可以利用这个触发删除页面缓存操作
onBeforeRouteLeave((to, from, next) => {
    if (from.name === "AppletPay") {
        storeBase.setInclude("AppletPay")
    }
    next()
})

onActivated(() => {
    getOneConfig()
})

onMounted(() => {
    getOneConfig()
})

onBeforeUnmount(() => {
    uploadOneRef.value = null
})

const tabName = ref("0")
const clickTab = (pane) => {
    uploadOneRef.value = null
    tabName.value = pane.index
}

/**
 * 添加小程序支付信息
 * @param {Boolean} form_loading 按钮状态
 * @param {Array} ruleRef 表单规则
 * @param {Object} ruleForm  表单字段
 * @param {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const showSecret = ref(false)
const oldOneSecret = ref({})
const ruleRef = ref(null)
const ruleForm = reactive({
    sh_name: "", // 商户名称
    app_secret: "", // 密钥
    app_secret_old: "", // 获取到密钥
    merchant_no: "", // 商户号
    fileList_two: [], // 证书之一，后缀apiclient_cert.pem
    two_paths: "",
    fileList_three: [], // 证书之一，后缀apiclient_key.pem
    three_paths: "",
    serial_no: "", // 序列号
})
const ruleCheck = reactive({
    sh_name: [{ required: true, message: "请输入商户名称", trigger: "blur" }],
    app_secret: [{ required: true, message: "请输入微信APIv3秘钥", trigger: "blur" }],
    merchant_no: [{ required: true, message: "请输入小程序支付商户号", trigger: "blur" }],
    two_paths: [{ required: true, message: "请选择小程序证书apiclient_cert.pem", trigger: "change" }],
    three_paths: [{ required: true, message: "请选择小程序证书apiclient_key.pem", trigger: "change" }],
})
// 提交
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                mch_title: ruleForm.sh_name,
                mch_id: ruleForm.merchant_no,
                mch_key: ruleForm.app_secret,
                apiclient_key: ruleForm.three_paths,
                apiclient_cert: ruleForm.two_paths,
            }
            proxy.$axios
                .post("payment/receive", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功", type: "success" })
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    showSecret.value = false
    uploadOneRef.value = null
    uploadTwoRef.value = null
    uploadThreeRef.value = null
    ruleForm.fileList_two = []
    ruleForm.fileList_three = []
}
const toBackOne = () => {
    ruleForm.sh_name = oldOneSecret.value.sh_name
    ruleForm.merchant_no = oldOneSecret.value.merchant_no
    ruleForm.app_secret_old = oldOneSecret.value.app_secret_old
    ruleForm.serial_no = oldOneSecret.value.serial_no
    showSecret.value = true
}
function getOneConfig() {
    proxy.$axios
        .get("payment/receiveInfo")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                if (result) {
                    oldOneSecret.value.sh_name = ruleForm.sh_name = result.mch_title
                    oldOneSecret.value.merchant_no = ruleForm.merchant_no = result.mch_id
                    oldOneSecret.value.app_secret_old = ruleForm.app_secret_old = result.mch_key
                    oldOneSecret.value.serial_no = ruleForm.serial_no = result.serial_no
                    showSecret.value = true
                }
                getTwoConfig()
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 添加商户转零钱信息
 * @param {Array} ruleTwoRef 表单规则
 * @param {Object} ruleTwoForm  表单字段
 * @param {Object} ruleTwoCheck  表单提示
 */
const showSecretTwo = ref(null)
const oldTwoSecret = ref({})
const ruleTwoRef = ref(null)
const ruleTwoForm = reactive({
    sh_name: "", // 商户名称
    app_secret: "", // 密钥
    app_secret_old: "", // 获取到密钥
    merchant_no: "", // 商户号
    fileList_two: [], // 证书之一，后缀apiclient_cert.pem
    two_paths: "",
    fileList_three: [], // 证书之一，后缀apiclient_key.pem
    three_paths: "",
    serial_no: "", // 序列号
})
const ruleTwoCheck = reactive({
    sh_name: [{ required: true, message: "请输入商户名称", trigger: "blur" }],
    app_secret: [{ required: true, message: "请输入微信APIv3秘钥", trigger: "blur" }],
    merchant_no: [{ required: true, message: "请输入小程序支付商户号", trigger: "blur" }],
    two_paths: [{ required: true, message: "请选择小程序证书apiclient_cert.pem", trigger: "change" }],
    three_paths: [{ required: true, message: "请选择小程序证书apiclient_key.pem", trigger: "change" }],
})
// 提交
const submitTwoForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                mch_title: ruleTwoForm.sh_name,
                mch_id: ruleTwoForm.merchant_no,
                mch_key: ruleTwoForm.app_secret,
                apiclient_key: ruleTwoForm.three_paths,
                apiclient_cert: ruleTwoForm.two_paths,
            }
            proxy.$axios
                .post("payment/pay", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功", type: "success" })
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetFormTwo = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    showSecretTwo.value = false
    uploadOneRef.value = null
    uploadTwoRef.value = null
    uploadThreeRef.value = null
    ruleTwoForm.fileList_two = []
    ruleTwoForm.fileList_three = []
}
const toBackTwo = () => {
    ruleTwoForm.sh_name = oldTwoSecret.value.sh_name
    ruleTwoForm.merchant_no = oldTwoSecret.value.merchant_no
    ruleTwoForm.app_secret_old = oldTwoSecret.value.app_secret_old
    ruleTwoForm.serial_no = oldTwoSecret.value.serial_no
    showSecretTwo.value = true
}
function getTwoConfig() {
    proxy.$axios
        .get("payment/payInfo")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                if (result) {
                    oldTwoSecret.value.sh_name = ruleTwoForm.sh_name = result.mch_title
                    oldTwoSecret.value.merchant_no = ruleTwoForm.merchant_no = result.mch_id
                    oldTwoSecret.value.app_secret_old = ruleTwoForm.app_secret_old = result.mch_key
                    oldTwoSecret.value.serial_no = ruleTwoForm.serial_no = result.serial_no
                    showSecretTwo.value = true
                }
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 上传证书-小程序支付配置
 * @param {Number} type 1是证书apiclient_cert.p12，2是证书apiclient_cert.pem，3是apiclient_key.pem
 * @param {Function} actionImgUrl 阻止上传地址
 * @param {Function} handleRemove 文件状态移除时的钩子
 * @param {Function} handleExceed 文件超出数量时的钩子
 * @param {Function} fileChange 文件状态改变时的钩子,
 * @param {Function} uploadFileOne 文件上传
 */
const uploadOneRef = ref(null)
const fileChange = (file, fileArr, type) => {
    if (tabName.value == 0) {
        type == 2 && (ruleForm.fileList_two = fileArr)
        type == 3 && (ruleForm.fileList_three = fileArr)
    } else {
        type == 2 && (ruleTwoForm.fileList_two = fileArr)
        type == 3 && (ruleTwoForm.fileList_three = fileArr)
    }
}
const handleExceed = (fileArr, type) => {
    if (type == 2) {
        uploadTwoRef.value.clearFiles()
        let file = fileArr[0]
        file.uid = genFileId()
        uploadTwoRef.value.handleStart(file)
    } else {
        uploadThreeRef.value.clearFiles()
        let file = fileArr[0]
        file.uid = genFileId()
        uploadThreeRef.value.handleStart(file)
    }
}
const handleRemove = (type) => {
    if (type == 2) {
        ruleForm.fileList_two = []
        ruleForm.two_paths = ""
    } else {
        ruleForm.fileList_three = []
        ruleForm.three_paths = ""
    }
}

/**
 * 上传证书 apiclient_cert.pem
 * @param {Function} uploadFileTwo 文件上传
 */
const uploadTwoRef = ref(null)
const uploadFileTwo = () => {
    if (ruleForm.fileList_two.length == 0 && tabName.value == 0) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    if (ruleTwoForm.fileList_two.length == 0 && tabName.value == 1) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    let data = new FormData()
    tabName.value == 0 && data.append("file", ruleForm.fileList_two[0].raw)
    tabName.value == 1 && data.append("file", ruleTwoForm.fileList_two[0].raw)
    proxy.$axios
        .post("upload/cert", data)
        .then((res) => {
            switch (res.data.code) {
                case 0:
                    if (tabName.value == 0) {
                        // ruleForm.fileList_two = []
                        ruleForm.two_paths = res.data.data.path
                    } else {
                        // ruleTwoForm.fileList_two = []
                        ruleTwoForm.two_paths = res.data.data.path
                    }
                    // uploadTwoRef.value.clearFiles()
                    proxy.$message({ message: "上传成功！", type: "success" })
                    break
                default:
                    proxy.$message({message:res.data.msg,type:"error"})
                    break
            }
        })
        .catch((err) => {})
}

/**
 * 上传证书 apiclient_key.pem
 * @param {Function} uploadFileThree 文件上传
 */
const uploadThreeRef = ref(null)
const uploadFileThree = (type) => {
    if (ruleForm.fileList_three.length == 0 && tabName.value == 0) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    if (ruleTwoForm.fileList_three.length == 0 && tabName.value == 1) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    let data = new FormData()
    tabName.value == 0 && data.append("file", ruleForm.fileList_three[0].raw)
    tabName.value == 1 && data.append("file", ruleTwoForm.fileList_three[0].raw)
    proxy.$axios
        .post("upload/cert", data)
        .then((res) => {
            switch (res.data.code) {
                case 0:
                    if (tabName.value == 0) {
                        // ruleForm.fileList_three = []
                        ruleForm.three_paths = res.data.data.path
                    } else {
                        // ruleTwoForm.fileList_three = []
                        ruleTwoForm.three_paths = res.data.data.path
                    }
                    // uploadThreeRef.value.clearFiles()
                    proxy.$message({ message: "上传成功！", type: "success" })
                    break
                default:
                    proxy.$message({message:res.data.msg,type:"error"})
                    break
            }
        })
        .catch((err) => {})
}

// 上传地址
function actionImgUrl() {
    return ""
}
</script>
<script>
export default {
    name: "AppletWxPay",
}
</script>

<style lang="less" scoped>
.el-form {
    margin-top: 30px;
}
.downs {
    margin-left: @margin-mdl;
}
:deep(.el-upload-list) {
    width: 500px;
    margin-top: 0;
}
.btn-submit {
    min-width: 100px;
    height: 36px;
}
</style>
